﻿using System;
using System.Web;

using Token.Piker.Core.Model;
using Token.Piker.Common;
using System.Web.SessionState;

namespace Token.Piker.Core.Security
{
    /// <summary>
    /// 权限管理器
    /// </summary>
    public class AuthzManager :IAuthzManager
    {
        public AuthzManager()
        {
        }

        /// <summary>
        /// 验证用户权限
        /// </summary>
        /// <param name="desiredRole">需要的权限</param>
        /// <returns>验证结果</returns>
        public EAuthenticateResult Validate(AbstractUser.ERole desiredRole)
        {
            //获得当前用户
            AbstractUser currUser = GetCurrentUser();

            //如果为空，则表示没登录
            if (currUser == null)
            {
                return EAuthenticateResult.NotLogged;
            }

            //如果权限满足要求，则放行
            if ((int)currUser.Role >= (int)desiredRole)
            {
                return EAuthenticateResult.Passed;
            }
            else
            {
                return EAuthenticateResult.AccessDeny;
            }
            
        }

        /// <summary>
        /// 获得sessionk中的当前用户
        /// </summary>
        /// <returns></returns>
        private AbstractUser GetCurrentUser()
        {
            if (HttpContext.Current == null) throw new ApplicationException("当前不存在Web应用的实例。");
            HttpSessionState Session = HttpContext.Current.Session; 
            AbstractUser au = new AbstractUser();
            if (Session[GlobalConstants.PIKER_USER_ID] != null)
            {
                au.Id = Session[GlobalConstants.PIKER_USER_ID].ToString();
                au.Username = Session[GlobalConstants.PIKER_USER_NAME].ToString();
                au.Role = AbstractUser.ERole.已验证;
            }
            else
            {
                au = null;
            }
            return au;
        }

    }
}